//
//  YHTextView.swift
//  EmotionKeyboard
//
//  Created by 昱含 on 16/6/1.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit

class YHTextView: UITextView {
    
    func insertEmotion(em: YHEmotions) {

        if em.isEmpty {
            return
        }
        
        if em.isDelete {
            deleteBackward()
            return
        }
        
        if em.emoji != nil {
            replaceRange(selectedTextRange!, withText: em.emoji ?? "")
        }
        
        let imageText = YHTextAttachment.emotionImageToImageText(em, font: font!)
        let strM = NSMutableAttributedString(attributedString: attributedText)
        let range = selectedRange
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        attributedText = strM
        selectedRange = NSMakeRange(range.location + 1, 0)
        self.delegate?.textViewDidChange?(self)

  }
    
    func fullText() -> String{
        let attr = attributedText
        var strM = String()
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) in
            //            print(dict)
            //            print("-------")
            //            print(range)
            if let attachment = dict["NSAttachment"] as? YHTextAttachment {
                
                //                print(attachment.chs)
                
                strM += (attachment.chs ?? "")
                print(strM)
                
            }else{
                
                let subStr = (self.text as NSString).substringWithRange(range)
                strM += subStr
                print(strM)
                
            }
        }
        
        return strM

    }
}
